//index.js
//获取应用实例
import encode from '../../utils/base64.js';
import request from '../../utils/config.js';
import formatDate from '../../utils/util.js';
import filter from '../../utils/filter.js';
let WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
const app = getApp();
Page({
  data: {
    newMessageList: "",
    caseInfoList: [],
    defaultName: "",
    defaultImg: "",
    personageData: "",
    ossImgUrL: 'https://winhc.oss-cn-shanghai.aliyuncs.com/xcx/',
    showModel:false,
    current:0,
    userExt:{},//用户扩展信息
    userType:'0',
    caseAndEntrustData:{
      caseNum:0,
      entrustNum:0
    },
    entrustId:"",
    identityType:'',
    mobileNo:""
  },


  //点击查看我的二维码
  goMyewm: function() {
    // this.getAppletQrCode();
    if (app.globalData.identity){
      wx.showModal({
        title: '对不起！您还未进行登录',
        content: '是否立即登陆',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../reg/reg',
            })
          } else if (res.cancel) {
          }
        }
      })
      return;
    }else{
      wx.navigateTo({
        url: '../card/newEditCard/newEditCard',
      })
    }
  },

  //获取小程序码access_token
  getAppletQrCode: function () {
    let qrUrl = "pages/card/otherIndex/otherIndex?openid=" + app.globalData.openid;
    console.log(qrUrl);
    var base64Code = encode.encode(qrUrl);
    app.globalData.qrData = request.request_url + "miniqrQr?path=" + base64Code + "&width=150";
    let transData = {
      name: app.globalData.persionalInfo.userName ? app.globalData.persionalInfo.userName : app.globalData.persionalInfo.nickName,
      avatarUrl: app.globalData.persionalInfo.avatarUrl
    }
    wx.navigateTo({
      url: '../card/appletQr/appletQr?transData=' + JSON.stringify(transData)
    })
  },


  // 拨打电话 
  callPhone: function () {
    var _this = this;
    wx.getSystemInfo({
      success: function (res) {
        // console.log('操作系统版本',res.system) //操作系统版本
        if (res.system.indexOf('iOS') != -1) {
          wx.makePhoneCall({
            phoneNumber: _this.data.personageData.mobileNo //仅为示例，并非真实的电话号码
          })
        } else if (res.system.indexOf('Android') != -1) {
          wx.showModal({
            title: '提示',
            content: '确定呼出电话？',
            success: function (res) {
              if (res.confirm) {
                wx.makePhoneCall({
                  phoneNumber: _this.data.personageData.mobileNo //仅为示例，并非真实的电话号码
                })
              } else if (res.cancel) {

              }
            }
          })
        }
      }
    })
  },

  caseApply: function() {
    wx.navigateTo({
      url: '../caseApply/caseApply/caseApply',
    })
  },

  //查看我申请的所有案件
  goMyApplyCase: function(){
    wx.navigateTo({
      url: '../myApplyCase/myApplyCase',
    })
  },

  //去案源库
  goCaseSrc: function(){
    wx.navigateTo({
      url: '../caseSrc/caseSrc',
    })
  },

  //点击委托悬赏
  goEntrustReward: function(){
    wx.navigateTo({
      url: '../caseReward/entrustReward/entrustReward',
    })
  },

  //去律师认证
  // go_lawyerConfirm: function () {
  //   wx.navigateTo({
  //     url: '../lawyerConfirm/lawyerConfirm',
  //   })
  // },
  //下拉执行
  onPullDownRefresh: function () {
    if (!app.globalData.userInfo) {
      this.setData({
        showModel: true
      })
    } else {
      if (!app.globalData.sessionId) {
        this.loginApi();
      } else {
        this.queryCaseInfoList();
      }
      setTimeout(function () {
        wx.stopPullDownRefresh();
      }, 1000);
    }
    console.log("执行了一次下拉刷新")
  },

  onShow: function () {
    let identityType = app.globalData.identity;
    this.setData({
      identityType: identityType
    });
    app.globalData.caseInfoList = "";
    if (!app.globalData.userInfo) {
      // 获取用户信息
      let _that = this;
      app.getAuthUserInfo((res)=>{
        console.log('首次获取用户信息=', res)
        // 可以将 res 发送给后台解码出 unionId
        res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
        app.globalData.userInfo = res.userInfo;
        app.globalData.encryptedData = res.encryptedData;
        app.globalData.iv = res.iv;
        _that.setData({
          defaultName: res.userInfo.nickName,
          defaultImg: res.userInfo.avatarUrl
        });
        // wx.showLoading({ title: '加载中', mask: true });
        _that.getOpenid(_that);
      },(res)=>{
        console.log("首次获取用户信息失败=", res)
        _that.setData({
          showModel: true
        })
      });
    } else {
      this.setData({
        defaultName: app.globalData.userInfo.nickName,
        defaultImg: app.globalData.userInfo.avatarUrl
      });
      if (!app.globalData.identity){
        if (!app.globalData.sessionId) {
          this.loginApi();
        } else {
          //此处由分享页面进入
          if (this.data.entrustId) {
            wx.navigateTo({
              url: '../caseReward/entrustDet/entrustDet?entrustId=' + this.data.entrustId
            })
          }
          this.queryCaseInfoList();
        }
      }else{
        //未登录游客身份进入
        this.queryCaseAndEntrust();
      }
    }
  },

  //组件授权回调
  _setAuthorization: function(e){
    let that = this;
    let res = e.detail;
    that.setData({
        defaultName: res.userInfo.nickName,
        defaultImg: res.userInfo.avatarUrl
      });
    that.getOpenid(that);
  },

  //获取openid
  getOpenid: (_that) => {
    // if (!app.globalData.userInfo) {
    //   wx.showLoading({
    //     title: '加载中',
    //   })
    // }
    request.request_api(app.globalData.code, (data) => {
      console.log("openid成功", data)
      if (data.statusCode != 200) {
        wx.showModal({
          title: '网络异常',
          content: '请尝试下拉界面重新加载',
          confirmText: '确定',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            } else if (res.cancel) {
            }
          }
        })
        return;
      }
      app.globalData.openid = data.data.openid;
      app.globalData.session_key = data.data.session_key;
      try {
        if (data.data.unionid) {
          app.globalData.unionid = data.data.unionid
        } else {
          //开始解析获取Unionid
          let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
          let decodeData = pc.decryptData(app.globalData.encryptedData, app.globalData.iv);
          // console.log('解密后 decodeData: ', decodeData);
          app.globalData.unionid = decodeData.unionid
        }
      } catch (e) {
        console.log("抛出异常=", e)
        //开始解析获取Unionid
        let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
        let decodeData = pc.decryptData(app.globalData.encryptedData, app.globalData.iv);
        // console.log('解密后 decodeData: ', decodeData);
        app.globalData.unionid = decodeData.unionid
      }
      
      if (!app.globalData.sessionId) {
        _that.loginApi();
        // wx.navigateTo({
        //   url: '../reg/reg',
        //   url:'../tourist/tourist'
        // })
      } else {
        // _that.queryMessage();
        _that.queryCaseInfoList();
      }
    }, (data) => {
      wx.hideLoading();
      console.log("openid失败", data)
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  //去名片页面
  goEditCard: function () {
    wx.navigateTo({
      url: '../card/cardIndex/cardIndex',
    })
  },

  //查询案源库以及委托悬赏数量
  queryCaseAndEntrust: function () {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId,
    }
    let bodyInfo = {
     
    }
    let _this = this;
    request.requestLogin_api("queryEntrustNums", headerInfo, bodyInfo, (obj) => {
      console.log("获取最新数量==", obj)
      if (obj.data.errorCode == '00'){
        let caseAndEntrustData = JSON.parse(obj.data.body);
        _this.setData({
          caseAndEntrustData: caseAndEntrustData
        });
      }else{
      
      }
    }, (obj) => {
      wx.hideLoading();
      wx.showModal({
        title: "查询数量失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    })
  },

  //查询案件列表
  queryCaseInfoList: function () {
    let headerInfo = {
      pageNum: "1",
      pageSize: "100",
      sessionId: app.globalData.sessionId,
    }
    let bodyInfo = {
      status: "",
      beginDate: "",
      endDate: "",
      keyword: ""
    }
    let _this = this;
    request.requestLogin_api("queryCaseInfoList", headerInfo, bodyInfo, (obj) => {
      console.log("获取案件列表==", obj)
      if (obj.data.isSuccess == "T") {
        let caseInfoList = JSON.parse(obj.data.body).caseInfoList;
        // let caseInfoList = new Array();
        if (caseInfoList.length > 0) {
          caseInfoList.forEach(function (e) {
            e.caseAmts = formatDate.filterFormatAmt(e.caseAmt * 1 / 10000);
            // e.status = formatDate.investStatusFilter(e.status);
            e.dateHM = filter.dateStr(e.applyDate) + ' ' + filter.timeHM(e.applyTime);
            e.bizStageStr = filter.bizStage(e.bizStage);
            e.caseAmtStr = filter.filterAmount(e.caseAmt) + filter.filterUnit(e.caseAmts);
          });

          app.globalData.caseInfoList = caseInfoList;
          //保存时间
          wx.setStorageSync("caseCacheTime", formatDate.formatTime(new Date()));
          _this.setData({
            caseInfoList: caseInfoList,
            // noMsg: false
          });
          wx.hideLoading();
        }
        _this.getCardLoginInfo(_this);
      } else {
        wx.hideLoading();
        wx.showModal({
          title: "查询案件列表失败",
          content: '请尝试下拉界面重新加载',
          confirmText: '确定',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              _this.getCardLoginInfo(_this);
            } else if (res.cancel) {
            }
          }
        })
      }
    }, (obj) => {
      wx.hideLoading();
      console.log("获取案件列表失败==", obj)
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    })
  },
  goCaseInfoDetail: function(e) { 
    console.log(e.currentTarget.dataset.id)
    let caseId = e.currentTarget.dataset.id;
    wx.navigateTo({
      // url: '../caseSrc/myCaseDetail/myCaseDetail?caseId=' + caseId,
      url: '../caseDescribe/caseDescribe?caseId=' + caseId,
    })
  },

  //获取登录名片信息
  getCardLoginInfo: (_that) => {
    //获取第三方接口登录数据
    let bodyInfo = {
      openid: app.globalData.openid,
      mobileNo: app.globalData.mobileNo,
      avatarUrl: app.globalData.userInfo.avatarUrl,
      nickName: app.globalData.userInfo.nickName,
      unionid: app.globalData.unionid
    };
    if (!app.globalData.userInfo) {
      wx.showLoading({
        title: '加载中',
      })
    }
    request.get_api("login", bodyInfo, (res) => {
      wx.hideLoading();
      console.log("获取登录名片信息成功=", res)
      let bodyData = JSON.parse(res.data.body);
      _that.getUserExt()
      if (res.data.isSuccess == 'T' && bodyData.memUserInfo.mobileNo) {
        //保存数据
        app.globalData.persionalInfo = bodyData.memUserInfo;
        let advField = "未填写";
        if (app.globalData.persionalInfo.advField) {
          advField = app.globalData.persionalInfo.advField.replace(/,/g, " | ");
        }
        let mobileNo = app.globalData.persionalInfo.mobileNo;
        mobileNo = String(mobileNo).substr(0, 3) + '-' + String(mobileNo).substr(3, 4) + '-' + String(mobileNo).substr(7, 4);
        // console.log('personageData', bodyData.memUserInfo)
        _that.setData({
          personageData: app.globalData.persionalInfo,
          fieldArea: advField,
          mobileNo: mobileNo
        });
        //查询案源库以及委托悬赏数量
        _that.queryCaseAndEntrust();

      } else {
        wx.hideShareMenu();
        _that.queryCaseAndEntrust();
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取信息失败=", res)
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },
  //获取扩展信息
  getUserExt:function(){
    //获取第三方接口登录数据
    let headerInfo = {
      sessionId: app.globalData.sessionId,
      pageNum: '',
      pageSize: '',
    },_this=this;
    request.requestLogin_api("queryUserExt", headerInfo,{}, (res) => {
      console.log("获取扩展信息", JSON.parse(res.data.body));
      if (res.data.isSuccess == 'T'){
        let bodyData = JSON.parse(res.data.body);
        _this.setData({
          userExt: bodyData,
          userType: bodyData.userType
        });
        app.globalData.userExt = JSON.parse(res.data.body);
        if (_this.data.entrustId) {
          wx.navigateTo({
            url: '../caseReward/entrustDet/entrustDet?entrustId=' + _this.data.entrustId
          })
        }
      }
    }, (res) => {
    });
  },

  onLoad: function (options) {
    this.queryCaseTypeList();
    if (options.entrustId){
      this.setData({
        entrustId: options.entrustId
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
      //清空entrustId的值
    if (this.data.entrustId){
      this.setData({
        entrustId: ""
      });
    }
  },

  /**
 * 生命周期函数--监听页面初次渲染完成
 */
  onReady: function () {
    this.toast = this.selectComponent("#toast");
  },

  //点击案件申请
  goWinhcCard: function () {
    if (app.globalData.openid) {
      wx.redirectTo({
        url: '../card/cardIndex/cardIndex',
      })
    } else {
      this.setData({
        showModel: true
      })
    }
  },

  //点击进入律师工具
  goLawyerTool: function () {
    wx.navigateTo({
      url: '../lawyerTool/selectType/selectType'
    })

  },

  // 显示我的律师
  goMyLawyer: function () {
    wx.navigateTo({
      url: '../myLawyers/myLawyers',
    })
  },


  //登录调用
  loginApi: function () {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: "",
    }
    let bodyInfo = {
      loginType: "mp",
      thirdLoginId: app.globalData.openid,
      unionid: app.globalData.unionid,
      nickName: app.globalData.userInfo.nickName,
      avatar: app.globalData.userInfo.avatarUrl,
      regChannel: '6'
    }
    let _this = this;
    request.requestLogin_api("userLogin", headerInfo, bodyInfo, (obj) => {
      console.log("erp登录系统返回成功=", obj)
      if (obj.data.isSuccess == "F" && obj.data.errorCode == "ERROR_NOT_REG") {
        //去选择身份验证页面
          _this.getLoginInfo(_this);
      } else if (obj.data.isSuccess == "T") {
        app.globalData.sessionId = obj.data.sessionId;
        //保存手机号
        app.globalData.mobileNo = JSON.parse(obj.data.body).mobileNo;
        app.globalData.userName = JSON.parse(obj.data.body).userName;
        _this.queryCaseInfoList();
      }else{
        wx.navigateTo({
          url: '../reg/reg',
        })
      }
    }, (obj) => {
      wx.hideLoading();
      console.log("用户登录失败=", obj)
      wx.showModal({
        title: "加载失败",
        content: '请尝试重新登录',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../reg/reg',
            })
          } else if (res.cancel) {
          }
        }
      })
    })
  },

  // 获取名片信息的接口
  getLoginInfo: (that) => {
    //获取第三方接口登录数据
    let bodyInfo = {
      openid: app.globalData.openid,
      mobileNo: app.globalData.mobileNo,
      unionid: app.globalData.unionid,
      nickName: app.globalData.userInfo.nickName,
      avatarUrl: app.globalData.userInfo.avatarUrl
    };
    let _this = that;
    request.get_api("login", bodyInfo, (res) => {
      wx.hideLoading();
      console.log("获取用户信息成功=", res)
      let bodyData = JSON.parse(res.data.body);
      if (res.data.isSuccess == 'T' && bodyData.memUserInfo.mobileNo) {
        //保存数据
        app.globalData.persionalInfo = bodyData.memUserInfo;
        app.globalData.mobileNo = bodyData.memUserInfo.mobileNo;
        _this.regErp(_this);
      } else {
        // wx.navigateTo({
        //   url: '../reg/reg',
        // })
        //去选择身份验证页面
        wx.redirectTo({
          url: '../tourist/tourist'
        })
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取用户信息失败=", res)
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  // 用户注册
  regErp: function (that) {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: "",
    }
    let bodyInfo = {
      loginType: "mp",
      thirdLoginId: app.globalData.openid,
      unionid: app.globalData.unionid,
      mobileNo: app.globalData.mobileNo,
      nickName: app.globalData.userInfo.nickName,
      avatar: app.globalData.userInfo.avatarUrl,
      regChannel: '6',
      mobileCheckNo: "SUCCESS"
    }
    let _that = that;
    request.requestLogin_api("userLogin", headerInfo, bodyInfo, (res) => {
      wx.hideLoading();
      console.log("注册成功=", res)
      app.globalData.sessionId = res.data.sessionId;
      app.globalData.userName = JSON.parse(res.data.body).userName;

      _that.queryCaseInfoList();
    }, (res) => {
      console.log("注册失败=", res)
      wx.showModal({
        title: "加载失败",
        content: '请尝试重新登录',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../reg/reg',
            })
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  //案件进展和我的案件进行切换
  // change_current:function(e){
    // let current = e.currentTarget.dataset.cur*1;
    // this.setData({ current: current})
  // },

  // 获取案件类型数据
  queryCaseTypeList: function (){
    let headerInfo = {
      pageNum: "1",
      pageSize: "",
      sessionId: app.globalData.sessionId,
    }
    let bodyInfo = {}
    let _this = this;
    console.log('headerInfo=', headerInfo)
    request.requestLogin_api("queryCaseTypeList", headerInfo, bodyInfo, (obj) => {
      if (obj.data.isSuccess == "T") {
        let caseTypeList = JSON.parse(obj.data.body).caseTypeList;
        console.log("获取案件类型数据", caseTypeList)

        //存储案件类型数据
        wx.setStorageSync('caseTypeListCache', JSON.stringify(caseTypeList))
      } else {
        wx.hideLoading();
      }
    }, (obj) => {
      wx.hideLoading();
      console.log("获取案件列表失败==", obj)
    })
  }
})
